package com.bridgeintelligent.tag.webserver.dim.query.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bridgeintelligent.tag.webserver.dim.query.api.DimAggregationRsp;
import com.bridgeintelligent.tag.webserver.dim.query.api.DimAnalysisRsp;
import com.bridgeintelligent.tag.webserver.dim.query.api.MultiDimAnalysisRsp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

import static javax.servlet.http.HttpServletResponse.SC_OK;

/**
 * @description 可群洞察到处
 * @author: grp 2020-11-09 16:09
 **/
@Api(tags = "ES导出")
@AllArgsConstructor
@RestController
@Slf4j
@RequestMapping(value = "/api/export")
public class CustomersExportController {

    private final QueryApiUtils queryApiUtils;

    @ApiOperation(value = "导出客群洞察", notes = "ES导出")
    @PostMapping("/customersAnalysis")
    public void export(String condition, HttpServletRequest request, HttpServletResponse response){
        log.info("接受参数："+condition);
        QueryApi queryApi = queryApiUtils.build(QueryApi.class);
        MultiDimAnalysisRsp dimAnalysisRsp = queryApi.customersMultiAnalysis(condition);
        List<DimAnalysisRsp.R> data = dimAnalysisRsp.getData();
        // 创建工作薄对象
        XSSFWorkbook workbook=new XSSFWorkbook();
        if(!CollectionUtils.isEmpty(data)){
            for(DimAnalysisRsp.R r : data){
                createSheet(r, workbook);
            }
        }else{
            XSSFSheet sheet=workbook.createSheet("模板");
            XSSFRow title = sheet.createRow(0);
            title.createCell(0).setCellValue("类型");
            title.createCell(1).setCellValue("客户数");
        }
        // 创建文档信息
        try(OutputStream os=response.getOutputStream()) {
            response.reset();
            response.setStatus(SC_OK);
            String fileName = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s.xlsx\"", fileName));
            response.setContentType("application/msexcel");
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
           log.error("可群洞察导出异常", e);
           throw new RuntimeException("导出异常");
        }
    }

    @ApiOperation(value = "客群洞察-动态聚合", notes = "动态聚合导出")
    @PostMapping("/customersDimAggregation")
    public void exportAgg( String condition, HttpServletRequest request, HttpServletResponse response){
        JSONArray parseArray = JSONArray.parseArray(condition);
        // 创建工作薄对象
        XSSFWorkbook workbook=new XSSFWorkbook();

        if (CollectionUtils.isNotEmpty(parseArray)){
            for (int i = 0; i < parseArray.size(); i++) {
                createAggSheet(workbook,parseArray.getString(i));
            }
        }else{
            XSSFSheet sheet=workbook.createSheet("模板");
            XSSFRow title = sheet.createRow(0);
            title.createCell(0).setCellValue("类型");
            title.createCell(1).setCellValue("客户数");
        }
        // 创建文档信息
        try(OutputStream os=response.getOutputStream()) {
            response.reset();
            response.setStatus(SC_OK);
            String fileName = "多维洞察分析-"+DateFormatUtils.format(new Date(), "yyyy-MM-dd");
            fileName = new String(fileName.getBytes(),"UTF-8");
            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s.xlsx\"", fileName));
            response.setContentType("application/msexcel");
            workbook.write(os);
            os.flush();
        } catch (IOException e) {
            log.error("多维洞察分析异常", e);
            throw new RuntimeException("多维洞察分析导出异常");
        }
    }


    private void createAggSheet(XSSFWorkbook workbook,String condition){
        log.info("请求："+ condition);
        QueryApi queryApi = queryApiUtils.build(QueryApi.class);
        DimAggregationRsp dimAggregationRsp = queryApi.customersDimAggregation(condition);
        log.info("响应："+ JSON.toJSONString(dimAggregationRsp));
        //动态新增字段
        List<String> fields = dimAggregationRsp.getFields();
        //动态字段映射
        Map<String,String> aggMap = dimAggregationRsp.getAggMap();

        XSSFSheet sheet=workbook.createSheet(dimAggregationRsp.getFieldName());
        XSSFRow title = sheet.createRow(0);
        title.createCell(0).setCellValue("类型");
        title.createCell(1).setCellValue("客户数");
        if (CollectionUtils.isNotEmpty(fields)){
            int m = 2;
            for (String field:fields) {
                title.createCell(m++).setCellValue(realName(field,aggMap));
            }
        }
        List<DimAggregationRsp.R> data = dimAggregationRsp.getData();
        if (data != null){
            int i = 1;
            for(DimAggregationRsp.R r:data){
                XSSFRow row = sheet.createRow(i++);
                row.createCell(0).setCellValue(r.getTitle());
                row.createCell(1).setCellValue(r.getCount());
                if (CollectionUtils.isNotEmpty(fields)){
                    int n = 2;
                    for (String field:fields) {
                        row.createCell(n++).setCellValue(realValue(field,aggMap,r.getInfo()));
                    }
                }
            }
        }

    }

    private String realValue(String field, Map<String,String> aggMap, List<DimAggregationRsp.Info> infos){
        String value = "";
        switch (aggMap.get(field)){
            case "max":
                value = infos.stream().filter(e -> e.getField().equals(field)).map(DimAggregationRsp.Info::getMaxValue).collect(Collectors.toList()).get(0);
                break;
            case "min":
                value = infos.stream().filter(e -> e.getField().equals(field)).map(DimAggregationRsp.Info::getMinValue).collect(Collectors.toList()).get(0);
                break;
            case "sum":
                value = infos.stream().filter(e -> e.getField().equals(field)).map(DimAggregationRsp.Info::getSumValue).collect(Collectors.toList()).get(0);
                break;
            default:
                value = infos.stream().filter(e -> e.getField().equals(field)).map(DimAggregationRsp.Info::getAvgValue).collect(Collectors.toList()).get(0);
        }
       return value;

    }

    private void createSheet(DimAnalysisRsp.R data, XSSFWorkbook workbook) {
        if(data==null||StringUtils.isBlank(data.getDimName())){
            return;
        }
        XSSFSheet sheet=workbook.createSheet(data.getDimName());
        XSSFRow title = sheet.createRow(0);
        title.createCell(0).setCellValue("类型");
        title.createCell(1).setCellValue("客户数");
        if(CollectionUtils.isEmpty(data.getInfo())){
            return;
        }
        int i = 1;
        for(DimAnalysisRsp.Info info:data.getInfo()){
            XSSFRow row = sheet.createRow(i++);
            row.createCell(0).setCellValue(info.getTitle());
            row.createCell(1).setCellValue(info.getCount());
        }
    }


    private static DimAggregationRsp makeData(){
        List<DimAggregationRsp.Info> list1 = new ArrayList<>();
        list1.add(DimAggregationRsp.Info.of().setField("age").setMaxValue("100.0").setMinValue("10.0").setAvgValue("55.0").setSumValue("110.0"));
        list1.add(DimAggregationRsp.Info.of().setField("money").setMaxValue("80.0").setMinValue("20.0").setAvgValue("50.0").setSumValue("100.0"));

        List<DimAggregationRsp.Info> list2 = new ArrayList<>();
        list2.add(DimAggregationRsp.Info.of().setField("age").setMaxValue("60.0").setMinValue("10.0").setAvgValue("35.0").setSumValue("70.0"));
        list2.add(DimAggregationRsp.Info.of().setField("money").setMaxValue("60.0").setMinValue("40.0").setAvgValue("50.0").setSumValue("100.0"));

        List<DimAggregationRsp.R> dataList = new ArrayList<>();
        dataList.add(DimAggregationRsp.R.of().setTitle("F").setCount(10).setInfo(list1));
        dataList.add(DimAggregationRsp.R.of().setTitle("M").setCount(5).setInfo(list2));

        List<String> fields = Arrays.asList(new String[]{"age","money"});

        Map<String,String> aggMap = new HashMap<>();
        aggMap.put("age","min");
        aggMap.put("money","max");
        aggMap.put("age_name","年龄");
        aggMap.put("money_name","金额");
        return DimAggregationRsp.of().setCode(0).setData(dataList).setFields(fields).setAggMap(aggMap);
    }

    private String realName(String field,Map<String,String> aggMap){
        String fieldName = Optional.ofNullable(aggMap.get(field+"_name")).orElse(field);
        StringBuffer buffer = new StringBuffer();
        return buffer.append(fieldName).append("(").append(aggMap.get(field)).append(")").toString();
    }


}
